package cn.lopr.im.android.mvp.view.activities;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

import cn.lopr.im.android.R;
import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.common.Constant;
import cn.lopr.im.android.common.app.Activity;
import cn.lopr.im.android.databinding.ActivityChatBinding;
import cn.lopr.im.android.db.entity.Message;
import cn.lopr.im.android.db.helper.DaoUtilsStore;
import cn.lopr.im.android.db.service.HomeDialogueDaoService;
import cn.lopr.im.android.db.service.MessageDaoService;
import cn.lopr.im.android.mvp.contact.IChatContact;
import cn.lopr.im.android.mvp.presenter.ChatPresenterImpl;
import cn.lopr.im.android.mvp.view.adapters.EmojiAdapter;
import cn.lopr.im.android.mvp.view.adapters.MsgAdapter;
import cn.lopr.im.android.service.MessageService;

public class ChatActivity extends Activity implements IChatContact.IChatView {

    private static String TAG = "ChatActivity";
    private ActivityChatBinding binding;
    private MsgAdapter msgAdapter;
    private ChatPresenterImpl chatPresenterImpl;

    private ArrayList<Integer> emojis = new ArrayList<>();

    private EmojiAdapter emojiAdapter;

    private MessageService.IMWebSocketClientBinder binder;

    private ChatMessageReceiver chatMessageReceiver;

    private User friend;

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //服务与活动成功绑定
            Log.e("ChatActivity", "服务与活动成功绑定");
            binder = (MessageService.IMWebSocketClientBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e("ChatActivity", "onServiceDisconnected: 服务与活动断开");
        }
    };

    @Override
    protected View getContentLayoutId() {
        binding = ActivityChatBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        this.chatPresenterImpl = new ChatPresenterImpl(this, this);
        doRegisterReceiver();
        initEmoji();

        this.binding.btnSend.setOnClickListener(e -> this.chatPresenterImpl.sendMessage());

        this.binding.ivBack.setOnClickListener(view -> ChatActivity.this.finish());

        this.binding.ivUserInfo.setOnClickListener(view -> {
            Intent intent = new Intent(ChatActivity.this, InfoActivity.class);
            intent.putExtra("user", friend);
            intent.putExtra("isFriend", true);
            startActivity(intent);
        });

        this.binding.ivEmoji.setOnClickListener(view -> {
            if (this.binding.emojiGrid.getVisibility() == View.VISIBLE) {
                this.binding.emojiGrid.setVisibility(View.GONE);
            } else {
                this.binding.emojiGrid.setVisibility(View.VISIBLE);
                this.closeInput();
            }
        });

        this.binding.etContent.setOnClickListener(view -> {
            Log.i(TAG, "initWidget: " + "click");
            this.binding.emojiGrid.setVisibility(View.GONE);
        });
    }

    private void initEmoji() {

        for (int i = 0; i < 107; i++) {
            if (i < 10) {
                int id = getResources().getIdentifier("f00" + i, "drawable", getPackageName());
                emojis.add(id);

            } else if (i < 100) {
                int id = getResources().getIdentifier("f0" + i, "drawable", getPackageName());
                emojis.add(id);

            } else {
                int id = getResources().getIdentifier("f" + i, "drawable", getPackageName());
                emojis.add(id);

            }
        }
        emojiAdapter = new EmojiAdapter(this, emojis);

        this.binding.emojiGrid.setAdapter(emojiAdapter);

        this.binding.emojiGrid.setOnItemClickListener((parent, view, position, id) -> {
            Log.i(TAG, "initEmoji: " + position + " " + id);
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), emojis.get(position));
            ImageSpan imageSpan = new ImageSpan(ChatActivity.this, bitmap);
            String str = null;
            if (position < 10) {
                str = "f00" + position;
            } else if (position < 100) {
                str = "f0" + position;
            } else {
                str = "f" + position;
            }
            SpannableString spannableString = new SpannableString(str);
            spannableString.setSpan(imageSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            this.binding.etContent.getText().insert(this.binding.etContent.getSelectionStart(), spannableString);
        });
    }

    @Override
    protected void initData() {
        super.initData();

        this.friend = (User) getIntent().getSerializableExtra("friend");

        // TODO 上拉刷新
        List<Message> messages = MessageDaoService.getMessage(this.friend.getPhone(),
                Constant.MessageType.SEND_TO_USER.getCode());
        MessageDaoService.setMessageIsRead(messages);
        HomeDialogueDaoService.setIsDelete(this.friend.getPhone(), 0);

        this.msgAdapter = new MsgAdapter(getApplicationContext(), messages, this.friend);

        binding.listMsg.setAdapter(msgAdapter);
        binding.tvName.setText(this.friend.getNickname());
    }

    private void doRegisterReceiver() {
        chatMessageReceiver = new ChatMessageReceiver();
        IntentFilter filter = new IntentFilter("cn.lopr.im.android.servicecallback.content");
        registerReceiver(chatMessageReceiver, filter);
    }

    public class ChatMessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }

            Message message = (Message) intent.getSerializableExtra("message");
            Log.e("ChatActivity: ", "onReceive: " + message);
            DaoUtilsStore.getInstance().getMessageDaoUtils().update(message.setIsRead(1));
            msgAdapter.addMessage(message);
        }
    }

    @Override
    public String getContent() {
        return this.binding.etContent.getText().toString();
    }

    @Override
    public void setContent(String value) {
        this.binding.etContent.setText(value);
    }

    @Override
    public void addMessage(Message value) {
        this.msgAdapter.addMessage(value);
    }

    @Override
    public void closeInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(binding.etContent.getWindowToken(), 0);
    }

    @Override
    public User getFriend() {
        return this.friend;
    }

    @Override
    public void finish() {
        overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
        super.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(chatMessageReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        ChatActivity.this.finish();
    }
}